package top.yehot.cmmu.spring.config;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

/**
 * 时间转化类
 * 
 * @author lquan
 * @date 2022年4月11日 下午2:45:18
 */
@Configuration
public class LocalDateTimeSerializerConfig {

	private final String yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
	private final String yyyyMMdd = "yyyy-MM-dd";
	
	@Bean
	public LocalDateTimeSerializer localDateTimeSerializer() {
		return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(yyyyMMddHHmmss));
	}
	
	@Bean
	public LocalDateSerializer localDateSerializer() {
		return new LocalDateSerializer(DateTimeFormatter.ofPattern(yyyyMMdd));
	}
	
	@Bean
	public DateSerializer dateSerializer() {
		return new DateSerializer(false, new SimpleDateFormat(yyyyMMddHHmmss));
	}

	@Bean
	public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
		Map<Class<?>, JsonSerializer<?>> map = new HashMap<Class<?>, JsonSerializer<?>>();
		map.put(LocalDateTime.class, localDateTimeSerializer());
		map.put(LocalDate.class, localDateSerializer());
		map.put(Date.class, dateSerializer());
		return builder -> builder.serializersByType(map);
	}
	
}
